const path = require("path");
const ci = require("miniprogram-ci");
const { shake } = require("@stack/utils");

const resolve = (filepath) => path.resolve(__dirname, filepath);

const projectConfig = {
  appid: "wx1671f8892ae4dcf2",
  type: "miniProgram",
  projectPath: resolve("../../packages/miniapp"),
  privateKeyPath: resolve("private.wx1671f8892ae4dcf2.key"),
  ignores: ["node_modules/**/*"],
};
const baseUploadConfig = {
  desc: "默认构建描述",
  version: "1.0.0",
  setting: {
    es6: true,
    codeProtect: true,
  },
  onProgressUpdate: () => {},
};

function createProject() {}

module.exports = class MiniappBuilder {
  constructor() {}

  createProject() {
    return new ci.Project(projectConfig);
  }
  
  async preview(config) {
    const project = this.createProject();
    const warning = await ci.packNpm(project, {
      ignores: [],
      reporter: () => {},
    });
    return ci.preview({
      project,
      ...{
        ...baseUploadConfig,
        ...shake(config),
      },
    });
  }

  async upload(config) {
    const project = this.createProject();
    const warning = await ci.packNpm(project, {
      ignores: [],
      reporter: () => {},
    });
    return ci.upload({
      project,
      ...{
        ...baseUploadConfig,
        ...shake(config),
      },
    });
  }

  createBuild(...args) {
    return () => this.build(...args);
  }

  parallelBuildCore(fns) {
    return Promise.all(fns.map((fn) => fn()));
  }

  serialBuildCore(fns) {
    let promise = Promise.resolve();
    for (const fn of fns) {
      promise = promise.then(() => fn());
    }
    return promise;
  }

  serialBuild(configs) {
    return this.serialBuildCore(
      configs.map((config) => this.createBuild(config))
    );
  }
};
